import { USER_TOKEN } from '@/constants/local-storage-key-const';
// import { decryptData, encryptData } from './encrypt';
// import { useUserStore } from '@/store/modules/system/user';

// const baseUrl = import.meta.env.VITE_APP_API_URL;
// const baseUrl = '/sa';
const baseUrl = '/api';

function getUserToken() {
  let token = uni.getStorageSync(USER_TOKEN);
  if (token) {
    return token;
  }
  return '';
}

/**
 * 通用请求封装
 */
export const request = function (url, method, data) {
  return new Promise((resolve, reject) => {
    uni.request({
      url: baseUrl + url,
      data: data,
      method: method,
      header: {
        'satoken': getUserToken(),
      },
      success: (response) => {
        const res = response.data;
        if (res.code && res.code !== 200) {
          // `token` 过期或者账号已在别处登录
          if (res.code === 401) {
            uni.showToast({
              title: res.msg,
              icon: 'none',
            });
            // useUserStore().clearUserLoginInfo();
            // uni.navigateTo({ url: '/pages/login/login' });
          }

          uni.showToast({
            title: res.msg,
            icon: 'none',
          });
          reject(response.data);
        } else {
          resolve(res);
        }
      },
      fail: (error) => {
        reject(error);
      },
    });
  });
};

export const getRequest = (url) => {
  return request(url, 'GET');
};

export const postRequest = (url, data) => {
  return request(url, 'POST', data);
};

/**
 * 加密请求参数的post请求
 */
export const postEncryptRequest = (url, data) => {
  return request(url, 'POST', { encryptData: encryptData(data) });
};
